<template>
<!-- 代码写的有点太冗余了，可以优化，还可以抽离成组件
     主要现在对封装组件的操作还有点不太熟悉
 -->
 
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>学生管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生信息</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <!-- 卡片试图区域 -->
  <el-card class="box-card">
    <!-- 搜索与添加区域 -->

    <el-row :gutter="20">
      <el-col :span="10">
        <!-- @keyup.enter.native="getSearchStudentByPage" 这个是按键修饰符， enter 键 -->
        <!-- 在按enter键的时候触发 getSearchStudentByPage() 函数 -->
        <el-input placeholder="请输入内容" @keyup.enter.native="getSearchStudentByPage" v-model="queryInfo.key">
          <template #append>
            <el-button
              icon="el-icon-search"
              @click="getSearchStudentByPage"
            ></el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" :disabled="addDisabled" @click="addDialogVisible = true"
          >添加学生</el-button
        >
      </el-col>

      <el-col :span="10" class="resetButton">
        <el-button type="success" plain @click="resetStudent" :disabled="resetDisabled"
          >恢复已删除的用户</el-button
        >
      </el-col>
    </el-row>
    <!-- 学生表格 -->
    <el-table :data="studentList" border stripe v-loading="loading">
      <el-table-column type="index" label="编号"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="年龄" prop="age"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="性别" prop="gender"></el-table-column>
      <el-table-column label="生日" prop="birthday"></el-table-column>
      <el-table-column label="描述" prop="info"></el-table-column>

      <!-- <el-table-column label="版本" prop="version"></el-table-column>
        //这里可以加一个布尔值的字段，来决定是否启用
        <template slot-scope="scope">
            {{results.flag}}
            <el-switch v-model="sope.row.version">

            </el-switch>
        </template> -->

      <el-table-column label="操作">
        <!-- 作用域插槽 -->
        <!-- 3.0语法是 v-slot 吧，要不出不来 -->
        <template v-slot="scope">
          <!-- 通过作用域插槽获取到id -->
          <!-- 供修改和删除时使用 -->
          <el-button
            round
            plain
            type="warning"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row.id)"
            :disabled="editDisabled"
            >修改</el-button
          >

          <el-button
            round
            plain
            @click="removeStudentById(scope.row.id)"
            type="danger"
            icon="el-icon-delete"
            :disabled="removeDisabled"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <!-- 这几个参数应该是：current-page：当前页，page-size：页面大小，total:总条数 -->
    <el-pagination
      class="block"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.pageNum"
      :page-sizes="[5, 10, 15, 30]"
      :page-size="query.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </el-card>

  <!-- 添加用户的对话框 -->
  <el-dialog
    title="添加学生"
    v-model="addDialogVisible"
    width="50%"
    @close="addDialogClosed"
    :disabled="addDisabled"
  >
    <!-- 内容主体区域 -->
    <el-form
      :model="addForm"
      :rules="addFormRules"
      ref="addFormRef"
      label-width="70px"
      v-loading="loading"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="addForm.name"></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-slider v-model="addForm.age" show-input> </el-slider>
        <!-- <el-input v-model="addForm.age"></el-input> -->
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="addForm.gender">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          v-model="addForm.birthday"
          type="date"
          placeholder="选择日期时间"
        >
        </el-date-picker>
        <!-- <el-input v-model="addForm.birthday"></el-input> -->
      </el-form-item>
      <el-form-item label="描述" prop="info">
        <el-input v-model="addForm.info"></el-input>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addStudent">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 这两个对话框其实是一样的 -->
  <!-- 修改用户对话框 -->
  <el-dialog
    title="修改学生"
    v-model="editDialogVisible"
    width="50%"
    @close="editDialogClosed"
  >
    <el-form
      :rules="editFormRules"
      ref="editFormRef"
      :model="editForm"
      label-width="80px"
      v-loading="loading"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="editForm.name"></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-slider v-model="editForm.age" show-input> </el-slider>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="editForm.gender">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          v-model="editForm.birthday"
          type="date"
          placeholder="选择日期时间"
        >
        </el-date-picker>
        <!-- <el-input v-model="addForm.birthday"></el-input> -->
      </el-form-item>
      <el-form-item label="描述" prop="info">
        <el-input type="textarea" autosize v-model="editForm.info"> </el-input>
        <!-- <el-input v-model="editForm.info"></el-input> -->
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editStudentInfo">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
//这是引入封装好的请求
import {
  insertStudent,
  searchStudent,
  getAllStudentByPage,
  getStudentById,
  updateStudent,
  deleteStudentById,
  resetStudentAll,
} from "../api/interface";
//这个是用来给后端传 @RequestParam 参数的吧
import QS from "qs";
import { dateFormat } from "../utils/date";
export default {
  data() {
    //直接百度就行了
    //验证邮箱的正则表达式
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    // 验证姓名正则
    const checkName = (rule, value, callback) => {
      const regName = /^[a-zA-Z\u4E00-\u9FA5\uf900-\ufa2d·s]{2,4}$/;
      if (regName.test(value)) {
        return callback();
      }
      callback(new Error("请输入正确的姓名"));
    };
    // 验证年龄正则
    const checkAge = (rule, value, callback) => {
      const regAge = /^(?:[1-9][0-9]?|1[01][0-9]|100)$/;
      if (regAge.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的年龄"));
    };
    // const checkBirthday = (rule, value, callback) => {
    //   const regBirthday = /^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/;
    //   if (regBirthday.test(value)) {
    //     return callback();
    //   }
    //   callback(new Error("请输入合法的日期"));
    // };

    return {
      //模糊查询获取到的学生的分页结果集
      queryInfo: {
        //查询参数
        key: "",
        //当前页
        pageNum: 1,
        //页面大小
        pageSize: 10,
      },
      //默认获取所有学生得到的分解结果集
      query: {
        //当前页数
        pageNum: 1,
        //每页条数
        pageSize: 10,
      },
      //学生列表
      studentList: [],
      //总条数
      total: 0,
      //加载效果
      loading: true,
      //按钮加载效果
      fullscreenLoading: false,
      //控制添加用户对话框的显式与隐藏
      addDialogVisible: false,
      //控制修改用户对话框的显式与隐藏
      editDialogVisible: false,
      //添加用户的表单数据
      addForm: {
        name: "",
        age: "",
        email: "",
        gender: "",
        birthday: "",
        info: "",
      },
      //修改用户的表单数据
      editForm: {},
      //按钮效果
      addDisabled: false,
      editDisabled: false,
      removeDisabled: false,
      resetDisabled: false,
      //添加表单的验证规则组件
      addFormRules: {
        name: [
          { required: true, message: "请输入姓名！", trigger: "blur" },
          { validator: checkName, trigger: "blur" },
        ],
        age: [
          { required: true, message: "请输入年龄！", trigger: "change" },
          { validator: checkAge, trigger: "change" },
        ],
        email: [
          { required: true, message: "请输入邮箱！", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        gender: [
          { required: true, message: "请选择性别！", trigger: "change" },
        ],
        birthday: [
          { required: true, message: "请选择日期！", trigger: "change" },
          // {validator: checkBirthday,trigger:"change"}
        ],
        info: [
          { required: true, message: "请输入描述信息！", trigger: "blur" },
          { max:28,message:"最多28个字!",}
        ],
      },
      //编辑表单的验证规则
      //重复度有点高了
      editFormRules: {
        name: [
          { required: true, message: "请输入姓名！", trigger: "blur" },
          { validator: checkName, trigger: "blur" },
        ],
        age: [
          { required: true, message: "请输入年龄！", trigger: "change" },
          { validator: checkAge, trigger: "change" },
        ],
        email: [
          { required: true, message: "请输入邮箱！", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        gender: [
          { required: true, message: "请选择性别！", trigger: "change" },
        ],
        birthday: [
          { required: true, message: "请选择日期！", trigger: "change" },
          // {validator: checkBirthday,trigger:"change"}
        ],
        info: [
          { required: true, message: "请输入描述信息！", trigger: "blur" },
          { max:28,message:"最多28个字!",}
        ],
      },
    };
  },
  methods: {
   
    //默认获取所有学生的分页结果集
    async allStudentListByPage() {
      //后端参数是 @RequestParam 需要将参数进行序列化
      //就用 QS.stringify ，vue自带的就有,引入就行了
      //  const result = await searchStudent(QS.stringify(this.queryInfo));
      //分页结果集
      const result = await getAllStudentByPage(QS.stringify(this.query));
      
      console.log(result)
      if (result.code == 401) {
        this.$message.warning("登录已过期");
        localStorage.removeItem("token");
        setTimeout(() => {
        location.reload();
        }, 1000);
      }
      //再搞一个延时哈哈
      setTimeout(() => {
        //给studentList赋值
        this.studentList = result.data.items;
        //给total赋值
        this.total = result.data.total;
        this.loading = false;
        //  if(result.code == 200){
        //      this.$message.success("获取信息成功")
        //  }
      }, 1000);
      // console.log(result);
    },

    //搜索获取学生分页结果集
    async getSearchStudentByPage() {
       //按键修饰符

      this.loading = true;
      const result = await searchStudent(QS.stringify(this.queryInfo));

      setTimeout(() => {
        //赋值
        this.studentList = result.data.items;
        this.total = result.data.total;
        this.loading = false;
      }, 1000);
    },

    //这个是无加载效果的
    async allStudentListByPages() {
      const results = await getAllStudentByPage(QS.stringify(this.query));
      //给studentList赋值
      this.studentList = results.data.items;
      //给total赋值
      this.total = results.data.total;
    },

    //监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.query.pageSize = newSize;
      //重新获取一下数据
      this.allStudentListByPages();
    },
    //监听 pageNum 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.query.pageNum = newPage;
      //重新获取一下数据
      this.allStudentListByPages();
    },
    //监听添加用户对话框的关闭时间
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //点击按钮添加新用户
    async addStudent() {
      //预验证吧，通过才会发起请求
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        //发起请求
        this.loading = true;
        const result = await insertStudent(this.addForm);
        
        // console.log(result);
        setTimeout(() => {
          this.loading = false;
          
          if (result.code == 200) {
            this.$message.success("添加学生成功");
          } else {
            this.$message.error("添加学生失败");
          }
          //关闭新增学生对话框
          this.addDialogVisible = false;
        }, 1500);
        //再重新获取一下数据就刷新了
        //获取的是无加载效果的
        this.allStudentListByPages();
      });
    },
    //展示编辑用户的对话框
    //通过作用域插槽获取到学生的id
    //再根据id查询学生就可以获取到单个学生的信息了
    async showEditDialog(id) {
      
      // console.log(id);
      //一直传不过去值，不知道怎么回事就行了
      const result = await getStudentById({ id });
      if(result.code == 403){
        this.$message.warning("抱歉您没有此操作权限");
        this.editDisabled = true;
        return;
      }
      this.loading = true;
      console.log(result)
      if (result.code != 200) {
        this.$message.error("获取信息失败");
      }

      setTimeout(() => {
        this.loading = false;
        //把查询到的信息存到 editForm
        this.editForm = result.data;
      }, 100);
      this.editDialogVisible = true;
    },
    //监听修改学生对话框的关闭时间
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //修改用户信息并提交
    editStudentInfo() {
      //预校验
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        //加载效果
        this.loading = true;
        //发起修改学生信息的请求
        //表单对应后端 @PutMapping 请求的话直接提交就行
        const result = await updateStudent(this.editForm);
        console.log(result);
        //加载效果
        setTimeout(() => {
          this.loading = false;
          if (result.code == 200) {
            //关闭对话框
            this.editDialogVisible = false;
            //重新调用 allStudentListByPage 获取数据刷新数据列表
            this.allStudentListByPage();
            //提示信息
            this.$message.success("修改成功");
          } else {
            this.$message.error("修改失败");
          }
        }, 1500);
      });
    },
    //根据id删除学生信息
    async removeStudentById(id) {
      //弹框询问是否删除
      const confirmResult = await this.$confirm(
        "此操作将删除该学生, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      //根据confirmResult的值来判断用户的操作
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const result = await deleteStudentById({ id });
      if(result.code == 403){
        this.$message.warning("抱歉您没有此操作权限");
        this.removeDisabled = true;
        return;
      }
      this.loading = true;
      // console.log(result)
      // console.log(id)
      if (result.code !== 200) {
        this.$message.error("删除失败");
      }

      setTimeout(() => {
        this.loading = false;
        //刷新列表
        this.allStudentListByPage();
        this.$message.success("删除成功");
      }, 1500);
    },
    //恢复已删除的所有学生
    //复制上面的，一样的
    async resetStudent(){
      //弹框询问是否恢复
      const confirmResult = await this.$confirm(
        "此操作将恢复所有已删除学生, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消");
      }
      
      const result = await resetStudentAll();
      if (result.code == 403) {
        this.$message.warning("抱歉您没有此操作权限");
        this.resetDisabled = true;
        return;
      }
      this.loading = true;
      // console.log(result)
      // console.log(id)
      if (result.code !== 200) {
        this.$message.error("恢复失败");
      }

      setTimeout(() => {
        this.loading = false;
        //刷新列表
        this.allStudentListByPage();
        this.$message.success("恢复成功");
      }, 1500);
    },
    
  },

  created() {
    this.allStudentListByPage();
    
    //挂载直接获取用户操作它的权力
    // this.addStudent();
    // this.allStudentListByPages()
  },
};
</script>

<style lang="less" scoped>
.resetButton{
  position: absolute;
  right: 4%;
}
</style>